#include "mystdio.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

MYFILE* my_fopen(const char* filename, const char* mode)
{
    int fd = -1;
    if(strcmp(mode, "w") == 0)
    {
        fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, UMASK); 
    }
    else if(strcmp(mode, "r") == 0) 
    {
        fd = open(filename, O_RDONLY);
    }
    else if(strcmp(mode, "a") == 0)
    {
        fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, UMASK);
    }
    else if(strcmp(mode, "a+") == 0)
    {
        fd = open(filename, O_RDWR | O_CREAT | O_APPEND, UMASK);
    }

    if(fd < 0)
    {
        return NULL;
    }

    MYFILE* fp = (MYFILE*)malloc(sizeof(MYFILE));
    if(!fp)
    {
        return NULL;
    }
    //初始化
    fp->fileno = fd;
    fp->flag = FLUSH_LINE;
    fp->curr = 0;
    fp->cap = SIZE;
    fp->outbuffer[0] = 0;

    return fp;
      
}

static void my_fflush_core(MYFILE* fp, int force)
{
    if(fp->curr <= 0)
    {
        return; 
    }
    //强制刷新
    if(force == FORCE)
    {
        if(fp->curr)
        {
            write(fp->fileno, fp->outbuffer, fp->curr);
            fp->curr = 0;
        }
        
    }
    else{
        //正常刷新
        if((fp->flag & FLUSH_LINE) && fp->outbuffer[fp->curr - 1] == '\n')
        {
            //行刷新
            write(fp->fileno, fp->outbuffer, fp->curr);
            fp->curr = 0;
        }
        else if((fp->flag & FLUSH_FULL) && fp->curr == fp->cap)
        {
            //全刷新
            write(fp->fileno, fp->outbuffer, fp->curr);
            fp->curr = 0;
        }

    }
}

int my_fwrite(const char* str, int size, MYFILE* fp)
{
    //写入
    strcpy(fp->outbuffer + fp->curr, str);
    fp->curr += size;
    my_fflush_core(fp, NOMAL);    

    return size;
}

void my_fflush(MYFILE* fp)
{
    if(fp != NULL)
    {
        my_fflush_core(fp, FORCE);
    }
}


void my_fclose(MYFILE* fp)
{
    if(fp->fileno >= 0)
    {
        my_fflush(fp);//语言级缓冲区->内核缓冲区
        fsync(fp->fileno);//内核缓冲区->磁盘
        close(fp->fileno);
        free(fp);
    }
}

